#include "board_adc.h"
#include "main.h"

#define ADC_VREF (*((uint16_t *)(0x1FFFFB0C))) // VREF1P0电压值（*10000）

static uint16_t g_adc_conv[8] = {0};
static uint16_t g_sun_voltage = 0;
// 分辨率为0.1ma
static uint16_t g_flasher_current = 0;
static uint32_t g_led_last_update_time = 0;

static uint16_t g_bat_small_voltage = 0;
static uint16_t g_vcc_voltage = 0;

static void board_adc_start_conv();

void board_adc_init()
{
    FL_VREF_EnableVREFBuffer(VREF); // 使能VREF BUFFER,
}

void board_update_volt()
{
    static uint16_t led_current_last = 0;
    static uint32_t ticks_ms_last = 0;
    uint16_t led_current_now = 0;
    uint32_t ticks_ms_now = sys_clock_get_ms();
    if (ticks_ms_now - ticks_ms_last < 100)
    {
        return;
    }

    ticks_ms_last = ticks_ms_now;
    if (g_adc_conv[4] != 0)
    {
        g_sun_voltage = (uint16_t)(((uint64_t)g_adc_conv[0] * ADC_VREF) / ((uint64_t)g_adc_conv[4] * 10));
        led_current_now = (uint16_t)(((uint64_t)g_adc_conv[1] * ADC_VREF) * 10 / ((uint64_t)g_adc_conv[4] * 25));
        g_vcc_voltage = (uint16_t)(((uint64_t)g_adc_conv[2] * ADC_VREF) * 41 / ((uint64_t)g_adc_conv[4] * 10));
        g_bat_small_voltage = (uint16_t)(((uint64_t)g_adc_conv[3] * ADC_VREF) * 23 / ((uint64_t)g_adc_conv[4] * 10 * 3));
        // user_printf("g_sun_voltage:%d\n", g_sun_voltage);             // 光感灯电压
        // user_printf("led_current_now:%d\n", led_current_now);         // 闪光器功率，没有电压，暂时不测、最后测
        // user_printf("g_vcc_voltage:%d\n", g_vcc_voltage);             // 电池电压，把bat焊出来做测试
        // user_printf("g_bat_small_voltage:%d\n", g_bat_small_voltage); // 小电池电压,9-15v做测试
    }

    if (led_current_now < 10)
    {
        led_current_now = 0;
    }

    if (led_current_now > 0)
    {
        if (abs(led_current_last - led_current_now) <= led_current_last * 0.1)
        {
            g_flasher_current = led_current_now;
        }
        g_led_last_update_time = sys_clock_get_ms();
    }

    led_current_last = led_current_now;

    // 开启下一次转换
    board_adc_start_conv();
}

// time must > 6ms
static void board_adc_start_conv()
{
    FL_DMA_ConfigTypeDef DMA_ConfigStruct = {0};
    DMA_ConfigStruct.memoryAddress = (uint32_t)g_adc_conv;
    DMA_ConfigStruct.transmissionCount = 4;
    FL_DMA_StartTransmission(DMA, &DMA_ConfigStruct, FL_DMA_CHANNEL_4);

    FL_ADC_ClearFlag_EndOfConversion(ADC); // 清标志
    FL_ADC_Enable(ADC);                    // 启动ADC
    FL_ADC_EnableSWConversion(ADC);        // 开始转换
}

uint16_t board_adc_get_light_volt()
{
    return g_sun_voltage;
}

uint16_t board_adc_get_bat_small_volt()
{
    return g_bat_small_voltage;
}

uint16_t board_adc_get_flasher_current()
{
    if (sys_clock_get_ms() - g_led_last_update_time > 700)
    {
        g_flasher_current = 0;
    }
    return g_flasher_current;
}

uint16_t board_adc_get_vcc_volt()
{
    return g_vcc_voltage;
}
